﻿// https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
// 106. 从中序与后序遍历序列构造二叉树

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <queue>
#include <limits.h>

using namespace std;

// struct ListNode {
//     int val;
//     ListNode *next;
//     ListNode() : val(0), next(nullptr) {}
//     ListNode(int x) : val(x), next(nullptr) {}
//     ListNode(int x, ListNode *next) : val(x), next(next) {}
// };

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.size() == 0 || postorder.size() == 0) return nullptr;
        return traversal(inorder, postorder);
    }

private:
    TreeNode* traversal(vector<int>& inorder, vector<int>& postorder) {
        if (postorder.size() == 0) return nullptr;

        int root_val = postorder[postorder.size() - 1];
        TreeNode *root = new TreeNode(root_val);

        if (postorder.size() == 1) return root;

        int mid_index;
        for (mid_index = 0; mid_index < inorder.size(); mid_index++) {
            if (inorder[mid_index] == root_val) break;
        }

        vector<int> left_inorder(inorder.begin(), inorder.begin() + mid_index);
        vector<int> right_inorder(inorder.begin() + mid_index + 1, inorder.end());

        postorder.resize(postorder.size() - 1);

        vector<int> left_postorder(postorder.begin(), postorder.begin() + left_inorder.size());
        vector<int> right_postorder(postorder.begin() + left_inorder.size(), postorder.end());

        root->left = traversal(left_inorder, left_postorder);
        root->right = traversal(right_inorder, right_postorder);

        return root;
    }
};

int main() {
    Solution obj = Solution();
}